﻿using Furion.DependencyInjection;
using Furion.EventBus;
using GMS.NET.Const;
using System.Reflection;

namespace GMS.NET.Application.EventBus
{
    /// <summary>
    /// 操作客户事件管理
    /// </summary>
    public class CustsEventSubscriber : DbManger, IEventSubscriber, ISingleton
    {
        [EventSubscribe(EventBusConst.CustsAddInitializeDataBase)]
        public Task CustsAddInitializeDataBase(EventHandlerExecutingContext context)
        {
            var custsParam = context.Source.Payload as CustsAddEventParam;
            string businessNameSpace = "GMS.NET.Core.Entitys.Business";
            var bizDb = BizDbInitialize(custsParam!.Connection!, custsParam!.Id!);
            //创建数据库
            bizDb.DbMaintenance.CreateDatabase();
            var entityTypes = App.EffectiveTypes.Where(t => t.Namespace == businessNameSpace && t.IsClass);
            foreach (var entityType in entityTypes)
            {
                if (entityType.IsDefined(typeof(SplitTableAttribute)))
                    bizDb.CodeFirst.SplitTables().InitTables(entityType);
                else
                    bizDb.CodeFirst.InitTables(entityType);
            }
            return Task.CompletedTask;
        }
    }

    public class CustsAddEventParam
    {
        public string? Connection { get; set; }
        public string? Id { get; set; }
    }
}
